var liveIM = require('../../utils/live-im') ;
var TIM = require('../../miniprogram_npm/tim-wx-sdk/index');
// var COS = require('../../miniprogram_npm/cos-wx-sdk-v5/index');
var WxParse = require('../../../wxParse/wxParse');
let levSet = require("../levSet") 
let smallIcon = require("../smallIcon")
var SVGA = require("../../utils/svga.min");
// var svgaParser = require("../../utils/svgaParser.min");

var app = getApp();

var timer=null,timer2=null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    menuButton:{}, //胶囊位置
    systemInfo:{}, //系统信息
    title:{}, //logo
    customerId:false, //获取手机号
    smallWindow:['push'], // 小窗口

    kefu:{yes:false, img:'', name:''}, // 是否客服
    liveData:{ //直播间数据
      connect_pull_url:'', //连麦
      connect_status:'0'
    },
    
    xcx_level_img:"",
    customer_level_img:"",
    xcx_level_name:"",
    customer_level:"",




    liveStart:false, //直播间状态
    lookCount:0, //观看量
    subscribe:0, //是否订阅
    tplID:null, //订阅消息id

    tabActive:0, // 导航栏
    tabViewHeight:200, // 功能区高度

    txtMsgList:[], //聊天室内容
    txtMsg:'', //聊天
    keyHeight:0, //键盘高度
    giftList:[], //礼物列表
    showGift:false, //礼物列表
    giftItem:{}, //选中礼物
    showCount:false, //礼物数量
    giftCountList:[1314,520,100,88,66,10,1], //礼物数量
    giftCount:1, //礼物数量
    giftSubmitStyle:'',
    gift:true, //礼物效果
    giftPoints:0, //积分
    giftTipList:[], //奖品提示列表
    giftTipList1:[], //奖品提示列表
    parserEnd:true,

    zanStart:0, //点赞动作
    zanCount:0, //点赞数量
    showZan:false, //点赞效果

    goodsList:[], //商品列表
    cradList:[], //卡券列表
    shareList:[], //达人帮列表

    showLottery:false, //抽奖弹框
    lotteryList:[], // 抽奖列表
    lotteryItem:{}, // 当前抽奖
    lotteryStatus:0, // 抽奖状态
    uuidYes:'', // 当前自己中奖口令
    lotteryHistory:[], // 中奖列表
    showLotteryHistory:false, //中将列表

    showModal:false, // 投诉弹窗

    showGoodsTip:false, //推送商品弹窗
    showContrastTip:false, //推送对比图弹窗
    showCradTip:false, //推送优惠券弹窗
    tipIdx:-1, //推送商品,优惠券
    showContrast:false, //对比图+商品弹窗

    goodsCountTipList:[],
    goodsMoneyTipList:[], //购买提示
    noMsg:[], // 禁言

    HB:{ // 红包
      id:'0', show:false,time:10
    },
    showQA:'',
    listQA:[],
    indexQA:0,
    timeQA:10,
    timeOutQA:null,
    rewardQA:false, //是否答题结束
    getQA:false, //是否有奖励

    URL:"",

    isShare:false,
    shareImg:"",

    gzText:"关注",
    produceIMG:"",

    recentuserlist:[],
    isScrollRow:false,

    qinmidu:0,
    singleQA: false,
    showQA1:false,
    
    pressState:true, // 礼物发送按钮状态
    gzTimer:null,
    gzCount:6,
    is_follow:0,
    is_describe:0,
    dyTxt:"+订阅",
    isGz:false,
    QAnumaward:-2
    


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    let t = this,token = wx.getStorageSync('ACCESS_TOKEN');
    // t.downLoadSVG()
    // console.log("SVGA",svgaParser)

    wx.setKeepScreenOn({keepScreenOn: true});
    token ? t.init(t,e,token) : app.page.onLoad(this, e);



    t.setData({
      levSet:levSet,
      smallIcon:smallIcon
    })

    

  },
  init(t,e,token){
    let d=t.data,
      menuButton=wx.getMenuButtonBoundingClientRect(),
      systemInfo=wx.getSystemInfoSync();
      // 导航栏高度  + 功能区域
    let tabViewHeight = 105 + 72 + menuButton.top + systemInfo.windowWidth*0.55;
    t.setData({
      menuButton,
      systemInfo,
      c_app:app,
      token:token,
      options:e,
      userInfo:wx.getStorageSync('USER_INFO'),
      tabViewHeight:Math.floor(tabViewHeight)
    },function () {
      t.data.kefu={yes:false, name:t.data.userInfo.nickname, img:t.data.userInfo.avatar_url}
      t.getLiveData(t,e,token);
      t.getGoodsList();
      t.getCradList();
      t.getShareList();
    })
  },

  toSynthesis(){
    var that=this
    console.log("123")
    this.setData({
      isShare:true
    })
    
    //创建画布
    const ctx = wx.createCanvasContext("ImgProduce", this)

    wx.downloadFile({
      url: this.data.shareImg,
      success (res) {
        if (res.statusCode === 200) {
            
              //网络背景图
              let bg=res.tempFilePath
              
              wx.getImageInfo({
                src: bg,
                success (res) {
                    console.log("codeImg",res)

                    let imgW = res.width
                    let imgH = res.height
                    let imgPath = res.path
                    

                    // this.setData({
                    //   canvasHeight: imgH,
                    //   canvasWidth: imgW
                    // })
                    // 绘制底图 用原图的宽高比绘制
                    ctx.drawImage(imgPath, 0, 0, 120, 120)
                    // ctx.draw()

                    ctx.drawImage('./code.png', 20, 20, 80, 80)
                    ctx.draw()


                     setTimeout(()=>{

                      wx.canvasToTempFilePath({
                        canvasId: 'ImgProduce',
                        success(res) {
                          console.log("produceIMG",res)
                          that.setData({
                            produceIMG:res.tempFilePath
                          })
                        }
                      })
 


                     },200)
 


                  }
              })
              



        }
      }
    })

   



  },
  delShare(){
    this.setData({
      isShare:false
    })
  },

  getLiveData(t,e,token){
    var d = t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/getRoomInfo',
      data:{
        hosId: app.api.siteinfo.hosId2,
        userId:token,
        liveId:e.id,
        oriToken:e.oriToken || ''
      },
      success(res){
        console.log(res)
        // live_status 1:直播中，2：已结束，3：未开始
        if(res.result == 0) {
          if(res.staffList.length){
            res.staffList.forEach(item=>{
              if(item.access_token == token){
                t.data.kefu={yes:true, name:item.nickname, img:app.api.siteinfo.logo}
              }
            })
          }
          d.txtMsgList.push({
            img:app.api.siteinfo.logo, name:'欢迎', token:'',
            enterRoom:true,
            txt: d.userInfo.nickname + ' 进入直播间',
            yes:false,admin:false
          })

          // 是否关注
          if(res.is_follow == 0) {
            t.setData({
              gzText:"关注",
              is_follow:0,
              is_describe:res.is_describe
            })
          }else{
            
            t.setData({
              gzText:"已关注",
              is_follow:1,
              is_describe:res.is_describe
            })
          }

          //qinmiduQA
          let qinmiduQA=res.qinmiduQA.data
          t.setData({
            qinmiduQA:qinmiduQA,
            topic: qinmiduQA[t.data.indexQA].question
          })
          // t.setQATime(res.qinmiduQA)

           //标签 与等级
           let xcx_level_img=res.xcx_level_img
           let customer_level_img=res.customer_level_img
           let customer_level=res.customer_level
           let xcx_level_name=res.xcx_level_name
           t.setData({
             subscribeTplID:res.subscribeTplID,
             xcx_level_img:xcx_level_img,
             customer_level_img:customer_level_img,
             customer_level:customer_level,
             xcx_level_name:xcx_level_name,
             qinmidu:res.qinmidu,
            //  topic:res.topic
           })


           let mylist= [
            ...res.recentuserlist,
            
          ]
         
          if(res.recentuserlist.length){
            // avatar_url
           
            if(mylist.length*20 > 120){
              console.log("aaa")
              t.setData({
                isScrollRow:true
              })
            }else{
              console.log("bbb")
              t.setData({
                isScrollRow:false
              })
            }


            t.setData({
              recentuserlist:mylist
            })
          }
            
 


          t.setData({
            liveData:res,
            lookCount:res.look_num || 0,
            zanCount:res.zan_num || 0,
            txtMsgList:d.txtMsgList,
            kefu:d.kefu,
            subscribe:res.subscribe,
            tplID:res.tplID,
            shareImg:res.share_img
          },function () {
            t.setInitIM(t,token,res);
            t.setLotteryList(res.lotteryData);
            t.setWxParse(res.liver_content);
          })
        }
      }
    })
  },

  // IM
  setInitIM(t,token,roomInfo){
    const configIM = {
      options:{SDKAppID:app.api.siteinfo.SDKAppID},
      setLogLevel:1,
      user:{
        userID: token,
        userSig: roomInfo.usersig
      },
      //群
      group:{ groupID: roomInfo.im_group_id, type: TIM.TYPES.GRP_AVCHATROOM },
      // 接受所有群消息
      message_received:t.getImMsg,
      error(e){console.log('error-1',e)}
    }
    liveIM.init(configIM,TIM,'',t);
  },
  getImMsg(e){
    console.log("信息类型",  e)
    let t = this;
    e.data.forEach(item=>{
      switch(item.type) {
        case 'TIMTextElem':
          console.log('普通信息')
          t.getTextMsg(t,item.payload.text)
          break;
        case "TIMCustomElem":
          t.getCustomMsg(item,t)
          break;
        default:
          console.log('未定义类型',item)
      }
    })
  },

  getCustomMsg(e,t){
    switch(e.payload.data) {
      case 'updateWatchList':
        if(JSON.parse(e.payload.extension).data.length*20 > 120){
          t.setData({
            isScrollRow:true,
            recentuserlist:JSON.parse(e.payload.extension).data
          })
        }else{
          t.setData({
            isScrollRow:false,
            recentuserlist:JSON.parse(e.payload.extension).data
          })
        }

        break;
      case "qinmidu":
        console.log("yes123",e.payload )
        t.setData({
          qinmidu:e.payload.extension
        })
        break;
      case 'pushZan':
        console.log('点赞量',e.payload.extension)
        t.setData({zanCount:t.data.zanCount+(e.payload.extension-0)})
        break;
      case "pushLook":
        console.log('观看量',e.payload.extension)
        t.setData({lookCount:t.data.lookCount+(e.payload.extension-0)})
        break;
      case "pullPlay":
        console.log('开播');
        t.setData({'liveData.live_status':1})
        break;
      case "pushMoney":
        console.log('购买',e.payload.extension);
        t.setMoneyTip(e.payload.extension)
        break;
      case "pushWXGoodsTips":
        console.log('商品剩余');
        t.setGoodsCountTip(e.payload.extension)
        break;
      case "updateGoods":
        console.log('更新商品');
        t.getGoodsList()
        break;
      case "updateCrad":
        console.log('更新卡券');
        t.getCradList()
        break;
      case "beginLottery":
        console.log('开始抽奖',e.payload.extension);
        t.startLottery(e.payload.extension)
        break;
      case "pullLottery":
        console.log('已开奖',e.payload.extension);
        t.endLotter(e.payload.extension)
        break;
      case "pullGoods":
        console.log('商品推送',e.payload.extension);
        let ex = JSON.parse(e.payload.extension);
        t.setGoodsTip(ex.goodsId,t);
        break;
      case "pullGoodsImg":
        console.log('对比图',e.payload.extension);
        t.setContrastTip(t,e.payload.extension)
        break;
      case "pullCoupon":
        console.log('优惠券',e.payload.extension);
        var data = JSON.parse(e.payload.extension)
        t.setCradTip(t,data.couponId)
        break;
      case "pullUrl":
        console.log('切换镜头',e.payload.extension);
        let ext = JSON.parse(e.payload.extension)
        t.setData({'liveData.pull_url':ext.url})
        break;
      case "pushChatMsg":
        console.log('自定义聊天',e.payload.extension);
        t.getTextMsg(t,e.payload.extension);
        break;
      case "pushGift":
        console.log('礼物',e.payload.extension);
        t.setGiftTip(JSON.parse(e.payload.extension))
        break;
      case "pullHB":
        console.log('红包',e.payload.extension);
        t.setHB(JSON.parse(e.payload.extension))
        break;
      case "pushWXQA":
        console.log('问答',e.payload.extension);
        t.setQATime(JSON.parse(e.payload.extension))
        break;
      case "pushgoodIdWant":
        console.log('想要',e.payload.extension);
        t.setWant(JSON.parse(e.payload.extension))
        break;
      case "pushConnectUrl":
        console.log('连麦',e.payload.extension);
        let o = JSON.parse(e.payload.extension);
        t.setData({
          'liveData.connect_status':o.status,
          'liveData.connect_pull_url':o.connect_url
        })
        break;
      default:
        console.log('未定义类型2',e)
    }
  },
  // 聊天室
  getTextMsg(t,e){
    var txt = JSON.parse(e);
    var txtMsgList = t.data.txtMsgList;
    if(txt.type){
      txt.admin=true;
      txt.name=t.data.liveData.adminchatname;
      txt.img=t.data.liveData.adminchatimg;
      txt.txt=txt.data.text;

      txt.type == 4 && t.data.goodsList.forEach((item,idx)=>{
        item.id == txt.data.goodsId && (txt.idx = idx);
      });
    }
    txtMsgList.push(txt);
    t.setData({txtMsgList},function () {
      t.data.tabActive || (t.data.keyHeight || wx.pageScrollTo({selector:'#footer'}))
    })
  },
  reply(e){ //回复消息
    let t = this,d=t.data,item=e.currentTarget.dataset.item;
    if(!d.kefu.yes || item.yes) return;
    console.log(item.name+': '+item.txt);
    t.setInput({},item.name+': '+item.txt);
  },
  // 禁言
  setNoMsg(e){
    var t = this,d=t.data,item=e.currentTarget.dataset.item;
    if(!d.kefu.yes || item.yes || item.admin) return;
    console.log('长按禁言',e);
    d.noMsg.push({
      text:'禁言: '+item.name,
      value:item.token
    });
    t.setData({noMsg:d.noMsg})
  },
  getNoMsg(e){
    let d = this.data;
    this.setData({noMsg:[]})
    if(e.type == 'actiontap'){
      app.request({
        url:getApp().api.siteinfo.apiroot+'live/forbidSendMsg',
        data:{
          hosId: app.api.siteinfo.hosId2,
          userID: e.detail.value,
          liveId: d.options.id
        },
        success(){wx.showToast({title:'禁言成功',icon:'none'})}
      })
    }
  },

  //商品列表
  getGoodsList(){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/getGoodsList',
      data:{
        hosId:app.api.siteinfo.hosId2,
        liveId:d.options.id
      },
      success(e){
        e.data.length && t.setData({goodsList:e.data})
      }
    })
  },
  //卡券列表
  getCradList(){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/couponBatchList',
      data:{
        storeId:app.api.siteinfo.acid,
        liveId:d.options.id
      },
      success(e){
        e.data.length && t.setData({cradList:e.data})
      }
    })
  },
  //达人帮列表
  getShareList(){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/shareInfoList',
      data:{
        hosId:app.api.siteinfo.hosId2,
        liveId:d.options.id,
        page:1,
        items:20,
      },
      success(e){
        e.shareList.length && t.setData({shareList:e.shareList})
      }
    })
  },

  // 礼物
  setShowGigt(){
    var t = this, d = t.data, customerId=wx.getStorageSync('customerId');
    if(d.giftList.length){
      t.setData({
        showGift:true, giftItem:d.giftList[0]
      });
      return;
    }
    console.log(customerId)
    if(customerId){
      // https://live.sgwxmini.com/beautyLive/getGiftListByCustomer?customerId=20211209105530070364&hosId=1
      wx.request({
        url:'https://live.sgwxmini.com/beautyLive/getGiftListByCustomer',
        data:{
          hosId:app.api.siteinfo.hosId2,
          customerId:customerId
        },
        success(e){
          console.log('请求数据',e)
          e.data.result == 0 && t.setData({
            giftList:e.data.giftList,
            showGift:true,
            giftPoints:e.data.customerPoints,
            giftItem:e.data.giftList[0]
          })
        }
      })
    }else {//access_token 08gmcwWlTT9PtCilS_5ApgLPYgJIexG7
      console.log(222)
      t.setData({customerId:true})
    }

  },
  setGiftItem(e){
    if(this.data.pressState){
      var item = e.currentTarget.dataset.item;
      this.setData({
        giftItem:item,
        showCount:false,
        giftCount:item.type?1:this.data.giftCount
      })
    }else{
      setTimeout(()=>{
        var item = e.currentTarget.dataset.item;
        this.setData({
          giftItem:item,
          showCount:false,
          giftCount:item.type?1:this.data.giftCount
        })
      },500)

    }
  },
  pressStart(){
      this.setData({
        pressState:false
      })
  },
  giftSubmit(){
    var t = this, d = t.data, customerId=wx.getStorageSync('customerId');
    this.setData({giftSubmitStyle:'',pressState:true})
    wx.request({
      url:'https://live.sgwxmini.com/beautyLive/giveGift',
      data:{
        hosId:app.api.siteinfo.hosId2,
        customerId:customerId,
        giftId:d.giftItem.id,
        count:d.giftCount,
        roomId:d.liveData.im_group_id,
        liveId:d.liveData.live_id
      },
      success(e){
        e.data.result ?
          wx.showToast({title:e.data.message,icon:'none'}) :
          t.sendGiftIM(t,d);
        t.setData({giftPoints:e.data.data.customerPoints,pressState:false})
      }
    })
    // t.sendGiftIM(t,d);
  },
  sendGiftIM(t,d){
    var item = {
      name:d.userInfo.nickname,
      img:d.userInfo.avatar_url,
      gift:d.giftItem,
      count:d.giftCount
    }
    var message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushGift',
        description: '礼物',
        extension: JSON.stringify(item)
      }
    });
    liveIM.tim.sendMessage(message);
    t.setGiftTip(item);
  },
  setGiftTip(item){
    var t= this, d = t.data;
    d.giftTipList.push(item);
    t.setData({giftTipList:d.giftTipList});
    item.gift.type && (d.giftTipList1.push(item),d.parserEnd && t.setGiftTip2());
  },
  downLoadSVG(){
    let that=this
    console.log("123")
    let link = 'https://image.sgwxmini.com/sglive/gift/svga/520.svga'
				//下载文件
				wx.downloadFile({
				  url: link,
				  success (res) {
				    if (res.statusCode === 200) {
					  //重新改写文件后缀
				      wx.getFileSystemManager().saveFile({
						  tempFilePath:res.tempFilePath,
						  //wx.env.USER_DATA_PATH 是微信提供了一个用户文件目录给开发者，开发者对这个目录有完全自由的读写权限
						  filePath:`${wx.env.USER_DATA_PATH}/hello.svga`,
						    success(res) {
  						    console.log( "URL",  res.savedFilePath) // res.savedFilePath 为一个本地缓存文件路径
							    that.setData({
                    URL:res.savedFilePath
                  })
  						  }
					  })
				    }
				  }
				})

  },

  setGiftTip2(){
    var t= this, d = t.data, l = d.giftTipList1;
    var parser = new SVGA.Parser(), player = new SVGA.Player("#myCanvas");
    d.parserEnd = false;
    l.length ?
    parser.load(l[0].gift.wx_svgaUrl, function (videoItem) {
      // parser.load('http://usr/svga2.svga', function (videoItem) {
      // console.log("SVAG666",videoItem)
      player.setVideoItem(videoItem);
      // let frame = videoItem.frames
      // console.log("rrrr",videoItem)
      player.loops=1;
      player.startAnimation();
      // player.startAnimationWithRange({location: parseInt(frame/2), length: frame- parseInt(frame/2)}, false);
      player.onFinished(function () {
        l.shift()
        
        t.setGiftTip2()
      })
    }) 

        //  (()=>{
               

        //          wx.request({
        //               url:l[0].gift.js_svgaUrl,
        //             //   url:`${wx.env.USER_DATA_PATH}/kxpc.js`,
        //               header: {
        //                 'content-type': 'application/json' // 默认值
        //               },
        //               success (res) {
                         
                          
        //                    player.setVideoItem(res.data);
        //                    let frame = res.data.frames
        //                    console.log("rrrr",res.data)
        //                     player.loops=1;
        //                     // player.startAnimation();
        //                     player.startAnimationWithRange({location: parseInt(frame/2), length: frame- parseInt(frame/2)}, false);
        //                     player.onFinished(function () {
        //                       l.shift()
        //                       t.setGiftTip2()
        //                     })
                      

                      
        //               },
        //           })
                

                //------------------------------------------------------------------
                // let data= getApp().globalData.testStr
                // console.log("rrrr",data)
                //             player.setVideoItem(data);
                //             player.loops=1;
                //             player.startAnimation();
                //             player.onFinished(function () {
                //               l.shift()
                //               t.setGiftTip2()
                //             })


                //---------------------------------------------------------------------
                // let fs = wx.getFileSystemManager();
                
                // fs.readFile({
                //   filePath:`${wx.env.USER_DATA_PATH}/520`+'.js',
                
                //   encoding:'utf-8',
                //   success: res => { 
                //     // replace(/\s/g,"")
                //     let obj = JSON.parse(res.data.replace(/\s/g,""))
                //     console.log("1111",obj)    

                //         player.setVideoItem(obj);
                //         player.loops=1;
                //         player.startAnimation();
                //         player.onFinished(function () {
                //           l.shift()
                //           t.setGiftTip2()
                //         })
                         
                 
                //         },
                //         fail: err =>{
                //             console.log("err",err)
                //         }
          
                //   })
              
        //  })() 
    : (d.parserEnd=true);
  },
  setShowCount(){
    var d = this.data;
    d.giftItem.type || this.setData({showCount:!d.showCount})
  },
  setGiftSubmitStyle(){
    this.setData({giftSubmitStyle:'gift-submit2'});
  },
  delGift(){this.setData({showGift:false})},
  delShowCount(e){this.setData({giftCount:e.currentTarget.dataset.item, showCount:false})},

  // 红包
  setHB(obj){
    this.setData({HB:{id:obj.hb_batch_id, time:obj.time, show:true}})
  },
  getHB(c){
    console.log(c.detail)
    this.setData({'HB.show':false})
    let d = this.data,hb = d.HB;
    if(!c.detail) return;
    wx.navigateTo({
      url:'/cheng/pages/money/money?id='+hb.id+'&count='+c.detail+'&liveId='+d.options.id
    })
  },
  // 点赞
  setZanCount(){
    let t = this;
    t.setData({
      showZan:true,
      zanStart: this.data.zanStart + 1,
      zanCount: this.data.zanCount + 1
    });


    if(timer2) clearTimeout(timer2);
    timer2 = setTimeout(function () {
      t.setData({showZan:false})
    },4000)


    let message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushZan',
        description: '点赞+1',
        extension: '1'
      }
    });
    liveIM.tim.sendMessage(message);
  },

  //输入框
  inputSubmit(){
    let t=this, d=t.data;
    if(!d.txtMsg) return;
    let l=d.txtMsgList;
    var txt = t.setPushTxtMsg(d.txtMsg);
    console.log("564",txt)
    l.push(txt)
    this.setData({txtMsgList:l, txtMsg:'',replyTxt:''})
  },
  setInput(e,replyTxt) {
    console.log(replyTxt);
    this.setData({showInput: true,txtMsg:'',replyTxt:replyTxt})
  },
  delInput(){
    this.setData({showInput: false, keyHeight:0,replyTxt:''})
  },
  inputText(e){this.setData({txtMsg:e.detail.value})},
  setHeight(e){
    this.setData({
      keyHeight:e.detail.height || 0
    },function () {
      e.detail.height || this.setData({txtMsg:''})
    })
  },


  // 发送聊天消息
  setPushTxtMsg(txt,type){
    let d = this.data,kefu=d.kefu;

    let xcx_level_img=d.xcx_level_img
    let customer_level_img=d.customer_level_img
    let xcx_level_name=d.xcx_level_name
    let customer_level=d.customer_level
    let bg=""
    if(xcx_level_name == '新粉'){ bg="rgb(38, 229, 115)" }
    if(xcx_level_name == '铁粉'){ bg="rgb(0 ,106, 230)" }
    if(xcx_level_name == '钻粉'){ bg="rgb(216, 99, 242)" }
    if(xcx_level_name == '挚爱粉'){ bg="rgb(254, 9,54)" }

    let txtMsg = { 
      img:kefu.img, 
      name:kefu.name,
      token:d.token,
      txt:txt, 
      yes:kefu.yes,
      replyTxt:d.replyTxt,
      xcx_level_img:xcx_level_img,
      customer_level_img:customer_level_img,
      customer_level:customer_level,
      xcx_level_name:xcx_level_name,
      enterRoom:false,
      bg:bg,
      type:type?type:null
    };

    let message = liveIM.tim.createTextMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {text:JSON.stringify(txtMsg)}
    })
    liveIM.tim.sendMessage(message);
    console.log(txtMsg)
    return txtMsg;
  },
  // 商品推送
  setGoodsTip(id,t){
    if(timer) clearTimeout(timer);
    console.log(id)
    t.data.goodsList.forEach((item,idx)=>{
      item.id == id && t.setData({
        showGoodsTip:true,
        tipIdx:idx,
        showContrastTip:false,
        showCradTip:false,
      },function () {
        timer = setTimeout(function () {
          t.setData({showGoodsTip:false})
        },600*1000)
      })
    })
  },
  //发送购买提示
  goGoods(ele){
    let d = this.data;
    let item = ele.currentTarget.dataset.item;
    if(item && item.want_type == 1) {this.want(item);return}
    let user = {
      name:d.userInfo.nickname.substring(0,2)+'**',
      img:d.userInfo.avatar_url,
    }
    let message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushMoney',
        description: '正在购买',
        extension: JSON.stringify(user)
      }
    });
    liveIM.tim.sendMessage(message);
    console.log(666);
    wx.navigateTo({url:ele.currentTarget.dataset.url})
  },

  //想要
  want(item){
    let t = this,d=t.data;

    wx.request({
      url:getApp().api.siteinfo.apiroot+'live/wantgood',
      data:{
        storeId:app.api.siteinfo.acid,
        liveId:d.options.id,
        access_token:d.token,
        good_id:item.id
      }
    })

  },
  setWant(obj){
    let t = this,d=t.data;
    let idx = d.goodsList.findIndex(i=>i.id==obj.goodsId);
    d.goodsList[idx].want_price = obj.want_price;
    d.goodsList[idx].want_count = obj.want_count;
    d.goodsList[idx].want_type = obj.want_type;
    this.setData({goodsList:d.goodsList})
  },
  // 对比图推送
  setContrastTip(t,d){
    var data = JSON.parse(d)
    if(timer) clearTimeout(timer);
    t.data.goodsList.forEach((item,idx)=>{
      item.id == data.goodsId && t.setData({
        showContrastTip:true,
        showContrast:true,
        contrastTip:data,
        tipIdx:idx,
        showGoodsTip:false,
        showCradTip:false,
        showGift:false
      },function () {
        timer = setTimeout(function () {
          t.setData({showContrastTip:false})
        },60*1000)
      })
    })
  },
  // 对比图+商品弹窗
  setContrast(){this.setData({showContrast:true})},
  delContrast(){this.setData({showContrast:false})},
  //优惠券推送
  setCradTip(t,id){
    if(timer) clearTimeout(timer);
    t.data.cradList.forEach((item,idx)=>{
      item.coupon_batch_id == id && t.setData({
        showCradTip:true,
        tipIdx:idx,
        showGoodsTip:false,
        showContrastTip:false,
      },function () {
        timer = setTimeout(function () {
          t.setData({showCradTip:false})
        },60*1000)
      })
    })
  },

  setGoodsCountTip(obj){
    let o = JSON.parse(obj);
    if(o.count - 0 > 10) return;
    let l = this.data.goodsCountTipList;
    let item = this.data.goodsList.find(i=>i.id == o.goodsId);
    item.count = o.count;l.push(item);
    this.setData({goodsCountTipList:l});
  },
  //购买提示
  setMoneyTip(obj){
    let o = JSON.parse(obj);
    let l = this.data.goodsMoneyTipList;
    l.push(o)
    this.setData({goodsMoneyTipList:l})
  },
  //领取卡券
  getCard(e){
    let idx = e.currentTarget.dataset.idx,
      toast = e.currentTarget.dataset.toast,
      t = this, d = t.data, card = d.cradList[idx];
    console.log(idx,card)
    if(card.is_over || card.status) return;
    let appUserInfo=wx.getStorageSync('appUserInfo');
    if(appUserInfo && appUserInfo.customerId){
      wx.request({
        url:getApp().api.siteinfo.apiroot+'live/grantCouponId',
        data:{
          storeId:app.api.siteinfo.acid,
          liveId:d.options.id,
          couponBatchId:card.coupon_batch_id,
          mobile:appUserInfo.mobile,
          customerId:appUserInfo.customerId,
          access_token:d.token
        },
        success(e){
          var tip = e.data.is_over?'已领完':(e.data.status?'领取成功':'领取失败')
          wx.showToast({title:tip,icon:'none'})
          e.data.coupon_name = e.data.couponBatchName;
          e.data.coupon_batch_id = e.data.couponBatchId;
          d.cradList[idx] = e.data
          t.setData({cradList:d.cradList})
        }
      })
    }else {
      t.setData({customerId:true})
    }
  },


  // 导航栏
  setTabActive(e){
    var idx = e.currentTarget.dataset.idx;
    this.setData({tabActive:idx});
    idx ? wx.pageScrollTo({scrollTop:0,duration:0}) : wx.pageScrollTo({selector:'#footer'});
    idx == 2 && this.getGoodsList();
    idx == 3 && this.getCradList();
    idx == 4 && this.getShareList();
  },

  // wxParse
  setWxParse(html){
    var that = this;
    WxParse.wxParse('html', 'html', html, that);
  },


  // 返回按钮
  navigateBack(){
    wx.navigateBack({
      delta: 1,
      success(){
        console.log('success')
      },
      fail(){
        wx.redirectTo({
          url: '/cheng/pages/live-list/live-list'
        })
      }
    })
  },
  //订阅
  setSubscribe(){
    var t = this,d = t.data;
    if(d.liveData.live_status != 3 || d.subscribe) return;
    wx.requestSubscribeMessage({
      tmplIds:d.tplID,
      success(e){
        JSON.stringify(e).indexOf('accept')>0 && t.pushSubscribe()
      }
    })
  },
  pushSubscribe(){
    var t = this,d = t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/subscribeLive',
      data:{
        hosId:app.api.siteinfo.hosId2,
        userId:d.token,
        liveId:d.liveData.live_id
      },
      success(e){
        wx.showToast({title:'订阅成功',icon:'none'})
        t.setData({subscribe:1})
      }
    })
  },


  // 所有抽奖信息
  setLotteryList(lotteryData){
    var t = this,d=t.data,item=null,list=null;
    list = lotteryData.filter((m,i)=>{
      if(m.lotteryStatus==1) item=m;
      return m.lotteryStatus>0;
    });
    if(list.length<1) return;
    item || (item = list[list.length-1])
    item.recordList.forEach(i=>{i.nickname = i.nickname.substring(0,2)+'**'})
    this.setData({
      lotteryItem:item,
      lotteryStatus:item.lotteryStatus,
      lotteryList:list
    })
  },
  startLottery(ext){
    var t = this,d = t.data;
    var ex = JSON.parse(ext),idx = -1;

    d.lotteryList.forEach((item,idx)=>{
      if(item.lotteryId == ex.lotteryId) idx = idx;
    })
    if(idx >= 0){
      d.lotteryList[idx] = ex;
    }else {
      d.lotteryList.push(ex)
    }
    console.log(5555)
    // 开始抽奖
    t.setData({
      lotteryStatus:1,
      lotteryItem:ex,
      lotteryList:d.lotteryList
    })
  },
  endLotter(ext){
    console.log(666)
    var t = this,d = t.data;
    // 中奖
    var ex = JSON.parse(ext),idx = -1;
    var lotteryItem,uuidYes='';

    d.lotteryList.forEach((item,idx)=>{
      if(item.lotteryId == ex.lotteryId) idx = idx;
    })
    if(idx >= 0){
      d.lotteryList[idx] = ex;
    }else {
      d.lotteryList.push(ex)
    }

    ex.recordList.forEach(item=>{
      item.nickname = item.nickname.substring(0,2)+'**'
      if(item.token == d.token){
        uuidYes = item.uuId
      }
    })
    t.setData({
      lotteryList:d.lotteryList,
      lotteryItem:ex,
      uuidYes,
      lotteryStatus:2,
      showLotteryHistory:false,
      showGift:false,
      showLottery:true
    })
  },
  // 中奖记录
  setLotteryHistory(){
    var t = this,d = t.data;
    var lotteryHistory = [];
    d.lotteryList.forEach(item=>{
      item.recordList.forEach(l=>{
        l.lotteryName = item.lotteryName
        lotteryHistory.push(l)
      })
    })
    t.setData({
      lotteryHistory,
      showLotteryHistory:true
    })
  },
  setShowLottery(){
    this.setData({
      showLottery:true
    })
  },
  delLottery(){
    this.setData({
      showLottery:false,
      showLotteryHistory:false
    })
  },
  setCopy(e){
    console.log(e)
    wx.setClipboardData({
      data:e.currentTarget.dataset.uuid
    })
  },
  

  // 投诉弹窗
  setModal(){
    this.setData({
      showModal:true
    })
  },
  delModal(){
    this.setData({
      showModal:false
    })
  },

  // 图片放大
  maxImage(e){
    console.log(e)
    var src = e.currentTarget.dataset.src;
    wx.previewImage({urls:[src]})
  },

  // 设置全屏
  setFullScreen(){
    var t=this,d=t.data;
    t.setData({
      smallWindow:[]
    },function () {
      wx.navigateTo({
        url:'/cheng/pages/live4/live4?url='+d.liveData.pull_url
      })
    })
  //   url:'/cheng/pages/live3/live3?id='+d.options.id
  },

   //开始答题
  startCurrentQA() {
    var that = this
    let obj = that.data.qinmiduQA
    console.log("obj", this.data.indexQA, obj)
    this.setData({
      showQA1: "123",
      listQA: obj.map(i => {
        i.select = [{
          v: i.answer_1,
          bg: ''
        }, {
          v: i.answer_2,
          bg: ''
        }, {
          v: i.answer_3,
          bg: ''
        }, {
          v: i.answer_4,
          bg: ''
        }];
        return i
      }),
      rewardQA: false,
      getQA: false,
      timeQA: 10,
      timeOutQA: null,
    }, this.startQA('single'))
  },

  // 问答
  setQATime(obj){
    this.hideQA1()
    this.setData({
      showQA:obj.reward,
      listQA:obj.data.map(i=>{
        i.select = [{v:i.answer_1,bg:''},{v:i.answer_2,bg:''},{v:i.answer_3,bg:''},{v:i.answer_4,bg:''}];
        return i
      }),
      rewardQA:false,
      getQA:false,
      indexQA:0,
      timeQA:10,
      timeOutQA:null,
      singleQA: false
    },this.startQA(''))
  },

  startQA(type){
    let t = this,d=t.data;
    if (type == 'single') { // 单题模式
      t.setData({
        singleQA: true
      })
      let timer = setInterval(() => { 
        if (d.timeQA > 0) {
          t.setData({
            timeQA: --d.timeQA,
            timeOutQA: timer
          })
        } else{
            t.setData({ rewardQA: true})
          }
        d.rewardQA && clearInterval(timer);
      }, 1000)
    }else{ 
      t.setData({
        singleQA: false
      })
      let timer = setInterval(()=>{
        if(d.timeQA>0){
          t.setData({timeQA:--d.timeQA,timeOutQA: timer})
        }else if(d.listQA.length-1>d.indexQA && d.listQA[d.indexQA].select.some(i=>i.bg)){
          t.setData({timeQA:10,indexQA:++d.indexQA,timeOutQA: timer})
        }else {
          t.setData({timeQA:10, indexQA:0, rewardQA:true,timeOutQA: timer})
        }
        d.rewardQA && clearInterval(d.timeOutQA);
      },1000)
    }
  },

  setABCD(e){
    let t = this,d=t.data;
    let idx = e.currentTarget.dataset.idx;
    let item = d.listQA[d.indexQA];
    let index = item.correct_answer-1;

    clearTimeout(d.timeOutQA);
    if(idx == index ){ //选对了
      item.select[idx].bg = '#57E46B';
      app.request({
        url:getApp().api.siteinfo.apiroot+'live/setqa',
        data:{
          group_id:item.group_id,question_id:item.question_id,
          answer:item.correct_answer,liveId:d.liveData.live_id,
          storeId:app.api.siteinfo.acid,
          is_single: d.singleQA ? 1 : undefined
        }})
    }else {
      item.select[idx].bg = '#F45742';
      item.select[index].bg = '#57E46B';
    }
    t.setData({listQA:d.listQA})
    if (d.singleQA) {
      clearInterval(d.timeOutQA);
      setTimeout(() => {  
        d.listQA.length > d.indexQA && idx == index ?
        t.setData({
          timeQA: 10,
          indexQA: ++d.indexQA,
        }, t.startQA('single'),clearInterval(d.timeOutQA)) :
        t.setData({
          timeQA: 10,
        }); 
        if (d.qinmiduQA.length > d.indexQA) {
          t.setData({
            topic: d.listQA[d.indexQA].question
          })
          if (idx == index) {
            t.setData({
              rewardQA: false,
            })
          } else {
            t.setData({
              rewardQA: true
            })
          }
        } else { 
          if (idx == index) {
            t.setData({
              rewardQA: true,
              getQA: true,
              QAnumaward:-2
            })
          }else{
            t.setData({ rewardQA: true})
          }
        }
       }, 1500)
    } else { 
      setTimeout(()=>{
        d.listQA.length-1>d.indexQA && idx == index?
            t.setData({timeQA:10, indexQA:++d.indexQA},t.startQA('')) :
            t.setData({timeQA:10, indexQA:0, rewardQA:true,getQA:idx == index });
      },1500)
    }
  },

  hideQA(){
    this.setData({showQA:'',listQA:[], timeQA:10,rewardQA:false,getQA:false})
  },

  hideQA1(){
    this.setData({
      showQA1: '',
      listQA: [],
      timeQA: 10,
      rewardQA: false,
      getQA: false
    })
  },
  
  savePhoto(){
    wx.saveImageToPhotosAlbum({
      filePath: this.data.produceIMG,
      success(res) {  
        wx.showModal({
          title: '温馨提示',
          content: '图片保存成功，可在相册中查看',
          showCancel: false,
        })

        this.setData({
          isShare:false
        })
      },

      fail(res) {
        wx.showModal({
          title: '温馨提示',
          content: '图片保存失败，请重试',
          showCancel: false
        })

        this.setData({
          isShare:false
        })
      },

      
    })




  },

  catchtap(){},

  toGz(){ 
    if(this.data.is_follow == 0){
      const _this = this
      let d=this.data
    const access_token = wx.getStorageSync('ACCESS_TOKEN')
    app.request({
        url: getApp().api.siteinfo.apiroot + "live/followLive",
        data: {
            hosId: app.api.siteinfo.hosId2,
            status:1,
            type:1,
            access_token:access_token,
            liveId: d.options.id
        },
        success(res) {
            if(res.data.code == 0){
              //im 
              let bg=""
              let xcx_level_name=_this.data.xcx_level_name
              if(xcx_level_name == '新粉'){ bg="rgb(38, 229, 115)" }
              if(xcx_level_name == '铁粉'){ bg="rgb(0 ,106, 230)" }
              if(xcx_level_name == '钻粉'){ bg="rgb(216, 99, 242)" }
              if(xcx_level_name == '挚爱粉'){ bg="rgb(254, 9,54)" }
              let txt = _this.setPushTxtMsg('关注了直播间','isFollow');
              txt.isFollow=true 
            console.log(txt)
            d.txtMsgList.push(txt)
            console.log( d.txtMsgList,' d.txtMsgList---')
              wx.showToast({
                title: '关注成功',
              })
               _this.setData({
                 is_follow:1,
                 txtMsgList:d.txtMsgList,
                 gzText:"已关注",
               })
               if(_this.data.is_describe==0){
                _this.setData({
                  isGz:true,
                  dyTxt:"+订阅"
                })
                if(!_this.data.gzTimer){
                  let timer = setInterval(()=>{
                    _this.setData({
                      gzCount:_this.data.gzCount - 1
                    })
                    if(_this.data.gzCount<=0){
                      clearInterval(timer)
                      _this.setData({
                        isGz:false,
                        gzTimer:null,
                        gzCount:6
                      })
                    }
                  },1000)
                  _this.setData({
                    gzTimer:timer
                  })
                }
               }
            }
        }
    })
    }else{
      console.log("l456",this.data.is_describe)
      if(this.data.is_describe ==0 && this.data.gzText=="已关注"){
        if(!this.data.gzTimer){
          let timer = setInterval(()=>{
            this.setData({
              gzCount:this.data.gzCount - 1
            })
            if(this.data.gzCount<=0){
              clearInterval(timer)
              this.setData({
                isGz:false,
                gzTimer:null,
                gzCount:6
              })
            }
          },1000)
          this.setData({
            gzTimer:timer
          })
        }
        this.setData({
          isGz:true
        })
      } 
    }
  },

  closeGz(){
    if(this.data.gzTimer){
      clearInterval(this.data.gzTimer)
    }
    this.setData({
      isGz:false,
      gzCount:6,
      gzTimer:null
    })
  },
  dingyue(){
    const _this = this
    let d = _this.data
    const access_token = wx.getStorageSync('ACCESS_TOKEN')
    wx.requestSubscribeMessage({
      tmplIds:[d.subscribeTplID],
      success(e){
        JSON.stringify(e).indexOf('accept')>0 && 
        app.request({
          url: getApp().api.siteinfo.apiroot + "live/followLive",
          data: {
              hosId: app.api.siteinfo.hosId2,
              status:1,
              liveId: d.options.id,
              access_token:access_token,
              type:2
          },
          success(res) {
              // console.log('判断邀约权限', res)
              if(res.data.code == 0){
                 _this.setData({
                   is_describe:1,
                   gzText:"已关注",
                   dyTxt:"已订阅"
                 })
                 wx.showToast({
                   title: '订阅成功',
                 })
              }
          }
      })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      smallWindow:['push']
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log(8888)
    liveIM.tim && liveIM.kill();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var d = this.data,l= d.liveData;
    return {
      title:l.room_name,
      path:'/cheng/pages/live2/live2?id='+l.live_id+'&oriToken='+d.token,
      imageUrl:d.produceIMG|| l.share_img
    }
  }
})